package com.watson.onebox.transaction;

import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import javax.naming.InitialContext;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import java.lang.reflect.Method;

/*
* 事务管理实现方式
* */
public class TxHandler implements InvocationHandler {

    private Object originalObject;
    public Object bind(Object obj) {

        this.originalObject = obj;
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
    }

    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Object result = null;
        if (!method.getName().startsWith("save")) {
            UserTransaction tx = null;
            try {
                tx = (UserTransaction) (new InitialContext().lookup("java/tx"));
                result = method.invoke(originalObject, args);
                tx.commit();
            } catch (Exception ex) {
                if (null != tx) {
                    try {
                        tx.rollback();
                    } catch (Exception e) {
                    }
                }
            }
        } else {
            result = method.invoke(originalObject, args);
        }
        return result;
    }

}
